package ca.cserkesz.healthform;

import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFileChooser;
import javax.swing.SwingWorker;
import javax.swing.filechooser.FileNameExtensionFilter;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;

/**
 *
 * @author Laza Gyuri cst. <laza.gyuri@cserkesz.ca>
 */
public class ExcelReader extends SwingWorker<ArrayList<Scout>, Void> {
    
    @Override
    public ArrayList<Scout> doInBackground() {
        
        
        try {
            
            JFileChooser openDialog = new JFileChooser();
            openDialog.setAcceptAllFileFilterUsed(false);
            openDialog.setFileFilter(new FileNameExtensionFilter("Excel fájl fajta", "xls", "xlsx"));
            openDialog.setMultiSelectionEnabled(false);
            openDialog.showOpenDialog(null);
            final File excelFile = openDialog.getSelectedFile();
            
            ArrayList<String> emptyCells = new ArrayList<String>(70);
            for (int i = 0; i < 70; ++i) {
                emptyCells.add("");
            }
            
            Sheet mySheet;
            /** Creating Input Stream**/
            FileInputStream myInput = new FileInputStream(excelFile);

            if (excelFile.getCanonicalPath().toLowerCase().endsWith(".xls")) {

                /** Create a POIFSFileSystem object**/
                POIFSFileSystem myFileSystem = new POIFSFileSystem(myInput);

                /** Create a workbook using the File System**/
                HSSFWorkbook myWorkBook = new HSSFWorkbook(myFileSystem);

                 /** Get the first sheet from workbook**/
                mySheet = myWorkBook.getSheetAt(0);
            } else {
                XSSFWorkbook myWorkBook = new XSSFWorkbook(myInput);

                mySheet = myWorkBook.getSheetAt(0);
            }

            /** We now need something to iterate through the cells.**/
            Iterator rowIter = mySheet.rowIterator();

            // Count number of rows
            int nRows = 0;
            while (rowIter.hasNext()) {
                rowIter.next();
                nRows++;
            }

            // Reset iterator
            rowIter = mySheet.rowIterator();

            int progress = 0;
            boolean header = true;
            ArrayList<Scout> list = new ArrayList<Scout>();
            while (rowIter.hasNext()) {
                progress++;

                Row row = (Row) rowIter.next();

                // Don't parse the header row
                if (header) {
                    header = false;
                    continue;
                }

                Iterator cellIter = row.cellIterator();
                ArrayList<String> cells = (ArrayList<String>) emptyCells.clone();
                while(cellIter.hasNext()){
                    Cell cell = (Cell) cellIter.next();                    
                    cells.add(cell.getColumnIndex(), cell.toString());
                }
                list.add(new Scout(cells));
                setProgress(progress * 100 / nRows);
            }

            return list;

        } catch (Exception ex) {
            Logger.getLogger(HealthFormController.class.getName()).log(Level.SEVERE, null, ex);
        }
        return null;
    }
}
